package com.i72.governance.init;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.i72.basic.consts.Consts;
import com.i72.basic.context.GlobalContext;
import com.i72.governance.service.bean.ServiceInfo;
import com.i72.governance.service.bean.ServiceNode;
import com.i72.governance.service.helper.ServiceHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;
import java.util.*;

@Slf4j
public class GovernanceServiceInit implements ApplicationListener<ContextRefreshedEvent>, Ordered {




    @Autowired
    private ServiceHelper serviceHelper;

    /**
     * 需要订阅的服务
     */
    //@Value("${governance.service.subscribeServices}")
    //private String subscribeServiceNameStr;

    /**
     * 当前应用名。
     */
    /*
    @Value("${governance.service.serviceName}")
    private String appName;

     */

    @Value("${server.port}")
    private String port;

    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        ApplicationContext applicationContext = event.getApplicationContext();
        this.applicationContext = applicationContext;

        if(GlobalContext.getRegister()){

             registerNode(GlobalContext.getProtocol());
        }

        if(GlobalContext.getSubscribe()){

            if(!StringUtils.isEmpty(GlobalContext.getSubscribelist())) {

                List<String> subscribeServiceNameList = Arrays.asList(GlobalContext.getSubscribelist().split(","));
                //订阅服务
                serviceHelper.subscribeService(subscribeServiceNameList);
            }
        }

    }







    private void registerNode(String protocol) {


        if(StringUtils.isEmpty(GlobalContext.getAPPPackage())){
            log.error("应用名与包名不一致或未实现任何服务");
            return;
        }

        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setServiceName(GlobalContext.getAPPName());

        List<ServiceNode> nodeList = new ArrayList<>();

        serviceInfo.setServiceNodes(nodeList);

        ServiceNode serviceNode = new ServiceNode();
        String address = GlobalContext.getIP();

        serviceNode.setEnvironment(GlobalContext.getEnvironment());
        serviceNode.setIp(address);
        serviceNode.setPort(new Integer(port));
        serviceNode.setProtocol(protocol);

        Map m = new HashMap();
        m.put(Consts.SERVICE_PACKAGE,GlobalContext.getAPPPackage());


        List<ServiceNode> instances = serviceHelper.pullServiceNode(GlobalContext.getAPPName());

        Map repet = new HashMap();
        if(instances!=null && instances.size()>0) {

            instances.forEach(i -> {
                Map mm = i.getMetadata();
                if (mm.containsKey(Consts.REFRESH_TIMESPAN)) {
                    repet.put(mm.get(Consts.REFRESH_TIMESPAN).toString(), "");
                }
            });
        }

        //获取随机时间间隔
        int MAX = 20;
        int MIN = 1;
        Random rand = new Random();
        Integer step1 = 3;
        Integer step2 = 5;
        Integer timespan = null;
        while (true){
            int randNumber =rand.nextInt(MAX - MIN + 1) + MIN;
            timespan = randNumber;
            if(!repet.containsKey(timespan.toString())){
                break;
            }
        }



        m.put(Consts.REFRESH_TIMESPAN,timespan);
        serviceNode.setMetadata(m);

        nodeList.add(serviceNode);

        //注册当前服务
        serviceHelper.addServiceInfo(serviceInfo);


        //GlobalContext.setProtocol(protocol);

        //初始化服务信息
        GlobalContext.setIP(address);
        GlobalContext.setPort(serviceNode.getPort());
        GlobalContext.setEnvironment(serviceNode.getEnvironment());
        GlobalContext.setConfigRefreshTimespan(timespan.toString());
        //GlobalContext.setAPPPackage(packageName);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+4;
    }
}
